package org.ttitfly.ttcore.web.menu;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.ttitfly.ttcore.entity.account.Role;
import org.ttitfly.ttcore.entity.account.User;
import org.ttitfly.ttcore.entity.menu.MenuItem;
import org.ttitfly.ttcore.entity.menu.SystemMenu;
import org.ttitfly.ttcore.service.account.RoleManager;
import org.ttitfly.ttcore.service.menu.SystemMenuManager;
import org.ttitfly.ttcore.web.CrudActionSupport;

import com.google.gson.Gson;

@SuppressWarnings("serial")
public class SystemMenuAction extends CrudActionSupport<SystemMenu>  {
	
	@Autowired
	private SystemMenuManager systemMenuManager;
	@Autowired
	private RoleManager roleManager;
	
	private Long id;
	
	private SystemMenu entity;
	
	List<SystemMenu> result = new ArrayList<SystemMenu>();
	
	public void setId(Long id) {
		this.id = id;
	}
	
	
	public Long getId() {
		return id;
	}
	public SystemMenu getModel() {
		return entity;
	}

	public String menuManager() throws Exception{
		return SUCCESS;
	}
	
	@Override
	public String list() throws Exception {
		// TODO Auto-generated method stub
		String keyword = (String) request.getParameter("keyword");
		SystemMenu menu = systemMenuManager.findByProperty("keyword", keyword);
		if(menu.getId() != null){
			result = systemMenuManager.findBy("parentId", menu.getId(),"orderNum",true);
		}
		return SUCCESS;
	}
	
	
	public String first() throws Exception{
		return SUCCESS;
	}
	
	public String initNode(){
		String strParentId = (String)request.getParameter("id");
		if(StringUtils.isBlank(strParentId)){
			strParentId = "0";
		}
		List<SystemMenu> list = systemMenuManager.findBy("parentId", Long.parseLong(strParentId),"orderNum",true);
		request.setAttribute("list", list);
		return SUCCESS;
	}
	/**
	 * 删除菜单节点
	 * @return
	 */
	public String systemMenuRemove(){
		SystemMenu menu = systemMenuManager.getById(id);//实际是SystemMenu的代理对象
		//Role是主控方，故需要通过Role来取消级联关系
		List<Role> roles = menu.getRoles();
		for(Role role : roles){
			List<SystemMenu> menus = role.getMenus();
			Iterator<SystemMenu> menusIt = menus.iterator();  
			while(menusIt.hasNext()){  
				SystemMenu menuIt = menusIt.next(); 
				if(menuIt.getId()==menu.getId()){
					menusIt.remove(); //取消级联关系 
				}
			}  
			role.setMenus(menus);
			roleManager.updateRole(role);
		}
		circleRemoveChild(menu);
		return null;
	}
	
	
	/**
	 * 删除所有的子菜单，子菜单和角色在关联表中不体现，故不需要牵涉到Role
	 */
	private void circleRemoveChild(SystemMenu menu){
		//级联关系已经被干掉，故可以直接删除SysteMenu对象
		systemMenuManager.remove(menu);
		List<SystemMenu> list = systemMenuManager.findBy("parentId", menu.getId(),"orderNum",true);
		for(SystemMenu sm : list){
			circleRemoveChild(sm);
		}
	}
	/**
	 * 备用
	 */
	private void circleRemoveChild(List<SystemMenu> menus){
		if(menus.size()==0){
			return;
		}else{
			for(SystemMenu menu : menus){
				List<SystemMenu> list = systemMenuManager.findBy("parentId", menu.getId(),"orderNum",true);
				systemMenuManager.remove(menu);
				circleRemoveChild(list);
			}
		}
	}
	/**
	 * 修改标题
	 * @return
	 */
	public String ajaxUpdateTitle() throws Exception{
		try{
			String newTitle = request.getParameter("newTitle");
			SystemMenu obj = systemMenuManager.getSystemMenu(id);
			obj.setTitle(newTitle);
			systemMenuManager.saveOrUpdate(obj);
			printJson("{success:true}");
		}catch(Exception e){
			printJson("{success:false}");
		}
		return null;
	}
	/**
	 * 保存节点
	 * @return
	 */
	public String systemMenuSave(){
		SystemMenu obj = null;
		String id = request.getParameter("id");
		String orderNum = request.getParameter("orderNum");
		String parentId = request.getParameter("parentId");
		String title = request.getParameter("title");
		String keyword = request.getParameter("keyword");
		String url = request.getParameter("url");
		String style = request.getParameter("style");
		Integer leaf = Integer.parseInt(request.getParameter("leaf"));
		if(StringUtils.isNotBlank(id)){
			obj = systemMenuManager.getSystemMenu(Long.parseLong(id));
			if(obj == null){
				return ERROR;
			}
		}else{
			obj = new SystemMenu();
		}
		obj.setLeaf(leaf);
		obj.setParentId(new Long(parentId));
		obj.setOrderNum(Integer.parseInt(orderNum));
		obj.setTitle(title);
		obj.setKeyword(keyword);
		obj.setUrl(url);
		obj.setStyle(style);
		systemMenuManager.saveOrUpdate(obj);
		return SUCCESS;	
	}
	
	/**
	 * 进入节点创建或者编辑页面
	 * @return
	 */
	public String systemMenuEdit(){
		List<User> users = systemMenuManager.findUsersByWorkflow("覆盖延伸", "新建项目", 32L);
		String parentId = request.getParameter("parentId");
//		String leaf = request.getParameter("leaf");
		String orderNum = request.getParameter("orderNum");
		String idStr = request.getParameter("id");
		SystemMenu systemMenu = new SystemMenu();
		String url = request.getParameter("url");
		//String style = request.getParameter("style");
		Integer leaf = 0;
		String strLeaf = request.getParameter("leaf");
		if(StringUtils.isNotBlank(strLeaf)){
			leaf = Integer.parseInt(strLeaf);;
		}
		 
//		if(parentId == null || "0".equals(parentId)){
//			leaf = 0;
//		}
		if(null != idStr){
			systemMenu = systemMenuManager.getSystemMenu(Long.parseLong(idStr));
		}else{
			systemMenu.setParentId(new Long(parentId));
			systemMenu.setLeaf(leaf);
			systemMenu.setOrderNum(new Integer(orderNum));
			systemMenu.setUrl(url);
		}
		request.setAttribute("entity", systemMenu);
		return SUCCESS;
		
	}
	
	
	@Override
	public String execute() throws Exception {
		
		MenuItem child1 = new MenuItem();
		child1.setCls("file1");
		child1.setId(11L);
		child1.setLeaf(true);
		child1.setChecked(false);
		child1.setChildren(null);
		child1.setText("S600");
		
		MenuItem child2 = new MenuItem();
		child2.setCls("file1");
		child2.setId(12L);
		child2.setLeaf(true);
		child2.setChecked(false);
		child2.setChildren(null);
		child2.setText("slK200");
		
		List<MenuItem> list = new ArrayList<MenuItem>();
		list.add(child1);
		list.add(child2);
		MenuItem parent = new MenuItem();
		parent.setCls("folderr1");
		parent.setId(9L);
		parent.setLeaf(false);
		parent.setChecked(false);
		parent.setChildren(list);
		parent.setText("Benz");
		
		
		List<MenuItem> result = new ArrayList<MenuItem>();
		result.add(parent);
		Gson gson = new Gson();
		
		String json = gson.toJson(result);
		printJson(json);
		
		return null;
	}

	@Override
	public String delete() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String input() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	protected void prepareModel() throws Exception {
		if (id != null) {
			entity = systemMenuManager.getSystemMenu(id);
		} else {
			entity = new SystemMenu();
		}
		
	}

	@Override
	public String save() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}


}
